#!/usr/bin/python3
u"""
记录log文件的python类.

《Python网络爬虫实战》胡松涛著 P99 的实例

使用了
logging模块：log主体
getpass模块：获取用户名


一共包含5个等级的异常信息
info
debug
warn
error
critical

验证程度依次递增，debug之后的均会导致程序终止
"""
import logging
import getpass
import os
import sys
from logging.handlers import RotatingFileHandler


class KeepLog():
    u"""记录log的类."""

    def __init__(self):
        u"""初始化."""
        self.run_dir = os.path.dirname(sys.argv[0])
        self.__set_log()

    def __set_log(self):
        # 添加的记录log的内容
        user = getpass.getuser()
        self.logger = logging.getLogger(user)
        self.logger.setLevel(logging.DEBUG)
        # 日志文件名
        logFile = sys.argv[0][:-3] + '.log'

        # 删除上一次运行的log文件
        formatter = logging.Formatter('%(asctime)-12s %(levelname)-8s' +
                                      ' %(name)-10s %(message)-12s')
        '''日志显示到屏幕上并且输出到日志文件内.'''
        logHand = logging.FileHandler(logFile)
        logHand.setFormatter(formatter)
        # 只有错误才会被记录到log中
        logHand.setLevel(logging.ERROR)
        # 控制log大小
        logHand = RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024,
                                      backupCount=2, encoding=None, delay=0)
        logHandSt = logging.StreamHandler()
        logHandSt.setFormatter(formatter)

        self.logger.addHandler(logHand)
        self.logger.addHandler(logHandSt)

    '''日志的五个等级.'''
    def debug(self, msg):
        u"""DEBUG等级."""
        self.logger.debug(msg)

    def info(self, msg):
        u"""INFO等级."""
        self.logger.info(msg)

    def warn(self, msg):
        u"""WARNING等级."""
        self.logger.warn(msg)

    def error(self, msg):
        u"""ERROR等级."""
        self.logger.error(msg)

    def critical(self, msg):
        u"""CRITICAL等级."""
        self.logger.critical(msg)
